package com.chuantou.yuba.ui.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.chuantou.yuba.R;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.request.MultiPartRequest;
import com.chuantou.yuba.api.to.BDPoiTO;
import com.chuantou.yuba.api.to.BaseTO;
import com.chuantou.yuba.api.to.CityTO;
import com.chuantou.yuba.api.to.FishingPlaceTO;
import com.chuantou.yuba.api.to.IdNameTO;
import com.chuantou.yuba.api.to.ImageTO;
import com.chuantou.yuba.api.to.UserTO;
import com.chuantou.yuba.ui.InputAddressActivity;
import com.chuantou.yuba.ui.LoginActivity;
import com.chuantou.yuba.util.AccountManager;
import com.chuantou.yuba.util.Constants;
import com.chuantou.yuba.util.UiUtil;

/**
 * 发布钓场界面
 * 
 * @author dl1001
 * 
 */
public class PublishFishingPlaceFragment extends AbsPublishNearFishingFragment {
	private static final List<IdNameTO> FISHING_PLACE_TYPE_LIST = new ArrayList<IdNameTO>();
	private static final List<IdNameTO> FISHING_COST_TYPE_LIST = new ArrayList<IdNameTO>();
	static {
		FISHING_COST_TYPE_LIST.add(new IdNameTO(1, "免费"));
		FISHING_COST_TYPE_LIST.add(new IdNameTO(2, "天塘"));
		FISHING_COST_TYPE_LIST.add(new IdNameTO(3, "斤塘"));

		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(1, "池塘"));
		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(2, "水库"));
		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(3, "江河"));
		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(4, "湖泊"));
		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(5, "海钓"));
		FISHING_PLACE_TYPE_LIST.add(new IdNameTO(6, "其他"));
	}

	private View mContentView;
	private EditText mNameView;
	private TextView mDistrictView;
	private TextView mAddressView;
	private TextView mFishingPlaceTypeView;
	private TextView mCostTypeView;
	private EditText mContactView;
	private EditText mPhoneView;
	private EditText mIntroduceView;
	private TextView mIntroduceCountView;
	private EditText mFeatureView;
	private TextView mFeatureCountView;
	private RecyclerView mRecyclerView;
	private CityTO mProvince;
	private CityTO mCity;
	private int mFishingPlaceType;
	// 默认免费
	private int mCostType = 1;
	// 需要编辑的钓场
	private FishingPlaceTO mPlace;

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mPlace = getArguments().getParcelable(Constants.EXTRA_SHOP);
		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.publish_fishing_place, null);
			mContentView.findViewById(R.id.district_layout).setOnClickListener(this);
			mContentView.findViewById(R.id.fishing_place_type_layout).setOnClickListener(this);
			mContentView.findViewById(R.id.cost_layout).setOnClickListener(this);
			mContentView.findViewById(R.id.address_layout).setOnClickListener(this);
			mNameView = (EditText) mContentView.findViewById(R.id.name);
			mDistrictView = (TextView) mContentView.findViewById(R.id.district);
			mAddressView = (TextView) mContentView.findViewById(R.id.address);
			mFishingPlaceTypeView = (TextView) mContentView.findViewById(R.id.fishing_place_type);
			mCostTypeView = (TextView) mContentView.findViewById(R.id.cost);
			mContactView = (EditText) mContentView.findViewById(R.id.contact);
			mPhoneView = (EditText) mContentView.findViewById(R.id.phone);
			mIntroduceView = (EditText) mContentView.findViewById(R.id.introduce);
			mIntroduceCountView = (TextView) mContentView.findViewById(R.id.introduce_count);
			mIntroduceView.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					int length = mIntroduceView.getText().length();
					mIntroduceCountView.setText(String.valueOf(200 - length));
				}
			});
			mFeatureCountView = (TextView) mContentView.findViewById(R.id.feature_count);
			mFeatureView = (EditText) mContentView.findViewById(R.id.feature);
			mFeatureView.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				}

				@Override
				public void afterTextChanged(Editable s) {
					int length = mFeatureView.getText().length();
					mFeatureCountView.setText(String.valueOf(30 - length));
				}
			});
			mRecyclerView = (RecyclerView) mContentView.findViewById(R.id.recyclerView);
			LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
			layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
			mRecyclerView.setLayoutManager(layoutManager);
			mRecyclerView.setAdapter(mImageAdapter);
			if (mPlace != null) {
				mNameView.setText(mPlace.getName());
				String district = String.format("%s %s", mPlace.getStateName(), mPlace.getCityName());
				mProvince = new CityTO();
				mProvince.setName(mPlace.getStateName());
				mProvince.setId(mPlace.getStateId());
				mCity = new CityTO();
				mCity.setName(mPlace.getCityName());
				mCity.setId(mPlace.getCityId());
				mDistrictView.setText(district);
				mAddressView.setText(mPlace.getAddress());
				int placeType = mPlace.getPlaceTypeNum();
				for (IdNameTO to : FISHING_PLACE_TYPE_LIST) {
					if (placeType == to.getId()) {
						mFishingPlaceType = to.getId();
						mFishingPlaceTypeView.setText(to.getName());
						break;
					}
				}
				int costType = mPlace.getPriceTypeNum();
				for (IdNameTO to : FISHING_COST_TYPE_LIST) {
					if (costType == to.getId()) {
						mCostType = to.getId();
						mCostTypeView.setText(to.getName());
						break;
					}
				}
				mContactView.setText(mPlace.getContact());
				mPhoneView.setText(mPlace.getPhone());
				mIntroduceView.setText(mPlace.getContent());
				mFeatureView.setText(mPlace.getFeature());
				setCoverView(mPlace.getImages());
			}
		}
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		return mContentView;
	}

	@Override
	public void onSubmit() {
		String name = mNameView.getText().toString().trim();
		if (TextUtils.isEmpty(name)) {
			Toast.makeText(mContext, R.string.input_name_error, Toast.LENGTH_SHORT).show();
			return;
		}
		if (mProvince == null || mCity == null) {
			Toast.makeText(mContext, R.string.input_district_error, Toast.LENGTH_SHORT).show();
			return;
		}
		String address = mAddressView.getText().toString().trim();
		if (TextUtils.isEmpty(address)) {
			Toast.makeText(mContext, R.string.input_fishing_detail_address_error, Toast.LENGTH_SHORT).show();
			return;
		}
		if (mFishingPlaceType <= 0) {
			Toast.makeText(mContext, R.string.input_fishing_place_type_error, Toast.LENGTH_SHORT).show();
			return;
		}
		String contact = mContactView.getText().toString().trim();
		if (TextUtils.isEmpty(contact)) {
			Toast.makeText(mContext, R.string.input_contact_error, Toast.LENGTH_SHORT).show();
			return;
		}
		String phone = mPhoneView.getText().toString().trim();
		if (TextUtils.isEmpty(phone)) {
			Toast.makeText(mContext, R.string.input_telephone_error, Toast.LENGTH_SHORT).show();
			return;
		}
		String introduce = mIntroduceView.getText().toString().trim();
		if (TextUtils.isEmpty(introduce)) {
			Toast.makeText(mContext, R.string.input_introduce_error, Toast.LENGTH_SHORT).show();
			return;
		}
		String feature = mFeatureView.getText().toString().trim();
		AccountManager accountManager = AccountManager.getInstance(mContext);
		if (!accountManager.isLogined()) {
			UiUtil.showNoLoginDialog(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		final UserTO user = accountManager.getUserTO();
		if (user.isExpired()) {
			Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
			LoginActivity.start(this, -1, LoginActivity.ACTION_RETURN);
			return;
		}
		final ProgressDialog dialog = new ProgressDialog(getActivity());
		dialog.setMessage(getString(R.string.uploading_fishing));
		dialog.setCancelable(false);
		dialog.show();
		String url = UriHelper.getAddFishingPlaceUrl();
		MultiPartRequest<BaseTO> request = new MultiPartRequest<BaseTO>(Method.POST, url, new Listener<BaseTO>() {

			@Override
			public void onResponse(BaseTO response) {
				if (getActivity() != null) {
					if (dialog != null && dialog.isShowing()) {
						dialog.dismiss();
					}
					if (response != null) {
						if (response.isSuccess()) {
							showUploadSuccessDialog();
						} else {
							if (response.getStatus() == BaseTO.STATUS_TOKEN_ERROR || response.getStatus() == BaseTO.STATUS_TOKEN_EXPIRED) {
								Toast.makeText(mContext, R.string.message_token_expired, Toast.LENGTH_SHORT).show();
								LoginActivity.start(getActivity(), -1, LoginActivity.ACTION_RETURN);
							} else {
								String msg = response.getMsg();
								msg = TextUtils.isEmpty(msg) ? getString(R.string.upload_failed) : msg;
								Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
							}
						}
					} else {
						Toast.makeText(mContext, R.string.upload_failed, Toast.LENGTH_SHORT).show();
					}
				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				if (getActivity() != null) {
					if (dialog != null && dialog.isShowing()) {
						dialog.dismiss();
					}
					Toast.makeText(mContext, R.string.request_error, Toast.LENGTH_SHORT).show();
				}
			}
		}, BaseTO.class);
		request.addStringUpload(UriHelper.PARAMS_UID, String.valueOf(user.getUid()));
		request.addStringUpload(UriHelper.PARAMS_TOKEN, user.getToken());
		request.addStringUpload(UriHelper.PARAMS_NAME, name);
		request.addStringUpload(UriHelper.PARAMS_CONTENT, introduce);
		request.addStringUpload(UriHelper.PARAMS_CONTACT, contact);
		request.addStringUpload(UriHelper.PARAMS_PHONE, phone);
		request.addStringUpload(UriHelper.PARAMS_ADDRESS, address);
		request.addStringUpload(UriHelper.PARAMS_FEATURE, feature);
		request.addStringUpload(UriHelper.PARAMS_PLACE_TYPE, String.valueOf(mFishingPlaceType));
		request.addStringUpload(UriHelper.PARAMS_PRICE_TYPE, String.valueOf(mCostType));
		request.addStringUpload(UriHelper.PARAMS_STATE_ID, mProvince.getId());
		request.addStringUpload(UriHelper.PARAMS_CITY_ID, mCity.getId());
		if (mPlace != null) {
			request.addStringUpload(UriHelper.PARAMS_ID, String.valueOf(mPlace.getId()));
		}
		List<ImageTO> images = mImageAdapter.getImages();
		int counter = 1;
		if (images != null && !images.isEmpty()) {
			for (ImageTO image : images) {
				if (image.getId() <= 0) {
					String path = Uri.parse(image.getUrl()).getPath();
					File file = new File(path);
					if (file.exists()) {
						request.addFileUpload("picture" + counter, file);
						counter++;
					}
				}
			}
		}
		List<Long> idList = new ArrayList<Long>();
		for (ImageTO image : mDeleteImages) {
			if (image.getId() > 0) {
				idList.add(image.getId());
			}
		}
		int size = idList.size();
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < size; i++) {
			buffer.append(idList.get(i));
			if (i != size - 1) {
				buffer.append(",");
			}
		}
		String ids = buffer.toString();
		if (!TextUtils.isEmpty(ids)) {
			ids = ids.substring(0, ids.length());
			request.addStringUpload(UriHelper.PARAMS_DEL_PHOTOS, ids);
		}
		RequestManager.startUpload(mContext, request);
	}

	@Override
	public void onCityPicked(CityTO province, CityTO city) {
		mProvince = province;
		mCity = city;
		String district = String.format("%s %s", mProvince.getName(), mCity.getName());
		mDistrictView.setText(district);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.district_layout:
			showProvinceDialog();
			break;
		case R.id.fishing_place_type_layout:
			showMenuListDialog(FISHING_PLACE_TYPE_LIST, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					IdNameTO to = FISHING_PLACE_TYPE_LIST.get(which);
					mFishingPlaceType = to.getId();
					mFishingPlaceTypeView.setText(to.getName());
				}
			});
			break;
		case R.id.cost_layout:
			showMenuListDialog(FISHING_COST_TYPE_LIST, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					IdNameTO to = FISHING_COST_TYPE_LIST.get(which);
					mCostType = to.getId();
					mCostTypeView.setText(to.getName());
				}
			});
			break;
		case R.id.address_layout:
			startActivityForResult(new Intent(getActivity(), InputAddressActivity.class), REQUEST_CODE_ADDRESS);
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != Activity.RESULT_OK)
			return;
		switch (requestCode) {
		case REQUEST_CODE_ADDRESS:
			BDPoiTO poi = data.getParcelableExtra(Constants.EXTRA_DATA);
			mAddressView.setText(poi.getAddress());
			break;
		default:
			break;
		}
	}
}
